#!/usr/bin/env bash
#
# ewlink - OpenWatcom owcc/wlink script for ELKS
#
# Usage: ewlink [-o binary] [--heap N] [--stack N] [-{owcc option}] file1.obj ...
#   produces file1.os2 (for OS/2) and file1 (for ELKS)
#
# 3 Jun 2024 Initial version
# 3 Jul 2024 Added -options for owcc and --options for wlink
#
set -e

if [ -z "$TOPDIR" ]
  then
    echo "ELKS TOPDIR= environment variable not set"
    exit
fi

if [ -z "$WATCOM" ]
  then
    echo "WATCOM= environment variable not set"
    exit
fi

ELKSLIBC=$TOPDIR/libc

# wlink options for debugging:
# -Wl,option -Wl,map              # produce mapfile (or use -fm=file.map)
# -Wl,option -Wl,verbose          # more detail in mapfile
# -Wl,option -Wl,static           # show static variables in mapfile
# -Wl,option -Wl,eliminate        # enable dead code elimination

LDFLAGS="\
    -bos2                           \
    -s                              \
    -Wl,option -Wl,start=_start     \
    -Wl,option -Wl,dosseg           \
    -Wl,option -Wl,nodefaultlibs    \
    -Wl,option -Wl,stack=0x1000     \
    -Wl,option -Wl,heapsize=0x1000  \
    -Wl,library -Wl,$TOPDIR/libc/libc.lib \
    "

while true; do
  case "$1" in
    --stack)
        LDFLAGS="$LDFLAGS -Wl,option -Wl,stack=$2"
        shift
        shift ;;
    --heap)
        LDFLAGS="$LDFLAGS -Wl,option -Wl,heapsize=$2"
        shift
        shift ;;
    -o)
        OUT=$2
        shift
        shift ;;
    -*)
        LDFLAGS="$LDFLAGS $1"
        shift ;;
    *)  break ;;
  esac
done

if [ $# -eq 0 ]
  then
    echo "Usage: ewlink [-o binary] [--heap N] [--stack N] [-{owcc option}] file1.obj ..."
    exit
fi

if [ "$OUT" == "" ]
  then
    PROG=$1
    OUT=${PROG%.obj}.os2
fi

echo owcc $LDFLAGS -o $OUT $@
owcc $LDFLAGS -o $OUT $@

# convert to ELKS a.out format
#os2toelks -f elks -o $OUT $OUT.os2

# dump OS/2 binary
#os2dump $OUT.os2

# copy to ELKS filesystem root user directory
#cp $OUT $TOPDIR/elkscmd/rootfs_template/root
